const findEle = (parent: { tagName: string; querySelector: (arg0: any) => any }, type: string) => {
  return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}

const trigger = (el: { dispatchEvent: (arg0: Event) => void }, type: string) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}

export default {
  mounted: function(el: { $inp?: any; tagName?: string; querySelector?: (arg0: any) => any }, binding: { value: any }) {
    // 正则规则可根据需求自定义
    const check = binding.value
    const $inp = findEle(el as any, 'input')
    el.$inp = $inp
    $inp.handle = function() {
      const val = $inp.value
      $inp.value = check(val)
      // console.log('val',val)
      trigger($inp, 'input')
    }
    $inp.addEventListener('blur', $inp.handle)
  },
  unmounted: function(el: { $inp: { removeEventListener: (arg0: string, arg1: any) => void; handle: any } }) {
    el.$inp.removeEventListener('blur', el.$inp.handle)
  }
}

